﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TemplateWizard;
using System.IO;
using System.Windows;

namespace RssReaderTemplate.Wizard
{
    public class SilentWizardRunner : WizardBase
    {
        public SilentWizardRunner(string projectDirectory)
        {
            _projectDirectory = projectDirectory;
        }
        public override void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            base.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
            if (CanRun)
            {
                ReadSettingsFromConfigFile(_projectDirectory);
                AddParameters(replacementsDictionary);
            }
        }

        private void ReadSettingsFromConfigFile(string projectPath)
        {
            try
            {
                var parentPath = Directory.GetParent(projectPath);
                var settings = File.ReadAllLines(Path.Combine(parentPath.FullName, "settings.txt"));
                TemplateParameters.ApplicationName = settings[0];
                TemplateParameters.ApplicationAuthor = settings[1];
                TemplateParameters.ApplicationEmail = settings[2];
                TemplateParameters.ApplicationContactWebpage = settings[3];
                TemplateParameters.ApplicationContactRssWebpage = settings[4];
                TemplateParameters.RssUrl = settings[5];
            }
            catch (Exception)
            {
                string message = @"The format of the settings file must be
                                   Application name
                                   Application author
                                   Author email
                                   Author webpage
                                   Original rss webpage
                                   Rss url";
                MessageBox.Show(message);
            }
        }

        private bool ThereIsAConfigFile(string projectPath)
        {
            var parentPath = Directory.GetParent(projectPath);
            return File.Exists(Path.Combine(parentPath.FullName, "settings.txt"));
        }

        public override bool CanRun
        {
            get
            {
                return ThereIsAConfigFile(_projectDirectory);
            }
        }
    }
}
